package com.bgds.sys.task;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

/**
 * @Description TODO
 * @Author lj
 * @create: 2020-09-04 15:30
 */
@Component
@Slf4j
public class CronSchedulerJob {
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;


    @Autowired
    private Scheduler scheduler;
    /**
     * 启动辊道段定时推送任务
     * @param deviceCode
     * @throws SchedulerException
     *    map.put("BLOCKED", "阻塞");
     *     map.put("COMPLETE", "完成");
     *     map.put("ERROR", "出错");
     *     map.put("NONE", "不存在");
     *     map.put("NORMAL", "正常");
     *     map.put("PAUSED", "暂停");
     */
    public void startRollerTask(String deviceCode,String id) throws SchedulerException {

        String state= getJobState(id,id);
        if("NONE".equals(state)){
            addJob(null,deviceCode,id,RollerJob.class,"0/5 * * * * ?");
        }else if ("NORMAL".equals(state)){
            Boolean flag= deleteJob(id,id);
            if(!flag){
                addJob(null,deviceCode,id,RollerJob.class,"0/5 * * * * ?");
            }
        }

    }

    /**
     * 启动辊轮定时任务
     * @param deviceCode
     * @param id
     * @throws SchedulerException
     */
    public void startWheelTask(String deviceCode,String id) throws SchedulerException {

        String state= getJobState(id,id);
        if("NONE".equals(state)){
            addJob(null,deviceCode,id,WheelJob.class,"0/5 * * * * ?");
        }else if ("NORMAL".equals(state)){
            Boolean flag= deleteJob(id,id);
            if(!flag){
                addJob(null,deviceCode,id,WheelJob.class,"0/5 * * * * ?");
            }
        }

    }

    /**
     * 综合看板定时任务
     */
    public void broadcast(){
        try {
            addJob(null,"broadcast","broadcast",SynthesizeBoardJob.class,"0/5 * * * * ?");
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    /**
     * 定时刷新设备事故
     */
    public void refresh(){
        try {
            //每一个小时 0 0 * * * ?
            addJob(null,"deviceFault","deviceFault",DeviceFaultJob.class,"0 1 * * * ? ");
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 助燃风机推送
     */
    public void startCombustionSupportFanTask(String relationId,String deviceCode,String id)throws SchedulerException {
        String state= getJobState(id,id);
        if("NONE".equals(state)){
            addJob(relationId,deviceCode,id,CombustionSupportingFanJob.class,"0/5 * * * * ?");
        }else if ("NORMAL".equals(state)){
            Boolean flag= deleteJob(id,id);
            if(!flag){
                addJob(relationId,deviceCode,id,CombustionSupportingFanJob.class,"0/5 * * * * ?");
            }
        }
    }

    /**
     * 除尘风机推送
     */
    public void startDedustFanTask(String relationId,String deviceCode,String id)throws SchedulerException {
        String state= getJobState(id,id);
        if("NONE".equals(state)){
            addJob(relationId,deviceCode,id,DedustFanJob.class,"0/5 * * * * ?");
        }else if ("NORMAL".equals(state)){
            Boolean flag= deleteJob(id,id);
            if(!flag){
                addJob(relationId,deviceCode,id,DedustFanJob.class,"0/5 * * * * ?");
            }
        }
    }

    /**
     * 除磷泵推送
     */
    public void startDiscalingPumpTask(String deviceCode,String id)throws SchedulerException {
        String state= getJobState(id,id);
        if("NONE".equals(state)){
            addJob(null,deviceCode,id,DiscalingPumpJob.class,"0/5 * * * * ?");
        }else if ("NORMAL".equals(state)){
            Boolean flag= deleteJob(id,id);
            if(!flag){
                addJob(null,deviceCode,id,DiscalingPumpJob.class,"0/5 * * * * ?");
            }
        }
    }

    /**
     * 监测点报警
     */
    public void startAlarmTask() {
        try {
            addJob(null,"alarm","alarm",AlarmJob.class,"0 */3 * * * ?");
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    /**
     * 添加任务，并启动
     * @param group
     */
    public void addJob(String relationId,String deviceCode, String group,Class clazz,String cornSchedule)throws SchedulerException {
        JobDetail job = JobBuilder.newJob(clazz)
                .withIdentity(group,group)
                //JobDataMap可以给任务传递参数
                .usingJobData("relationId",relationId)
                .usingJobData("deviceCode",deviceCode)
                .usingJobData("id",group)
                .build();

        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cornSchedule);
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity(group,group)
                .withSchedule(scheduleBuilder).build();
        scheduler.scheduleJob(job,cronTrigger);
    }
    /**
     * 获取Job信息
     *
     * @param name
     * @param group
     * @return
     * @throws SchedulerException
     */
    public String getJobState(String name, String group) throws SchedulerException {
        TriggerKey tk=new TriggerKey(name,group);
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        log.info("信息：{}",jobDetail) ;
        log.info("状态：{}",scheduler.getTriggerState(tk).name()) ;
        log.info("信息：{}",scheduler.checkExists(jobKey)) ;
        return scheduler.getTriggerState(tk).name();
    }
    /**
     * 暂停某个任务
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void pauseJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        scheduler.pauseJob(jobKey);
    }
    /**
     * 恢复某个任务
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void resumeJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);

        scheduler.resumeJob(jobKey);
    }
    /**
     * 删除某个任务
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public boolean deleteJob(String name, String group) throws SchedulerException {
        Boolean flag=null;
        try {
            // TriggerKey 定义了trigger的名称和组别 ，通过任务名和任务组名获取TriggerKey
            TriggerKey triggerKey = TriggerKey.triggerKey(name,group);
            // 停止触发器
            scheduler.resumeTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            // 移除任务
            flag= scheduler.deleteJob(JobKey.jobKey(name,group));

        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return flag;
    }
}
